package com.example.xianji.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.bean.YiJi_Class;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;

import android.os.Bundle;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 发布求购有发布产品的求购和发布服务的求购两种
 *
 * @author me
 */
public class Main_Send_Want_Buy_ProductActivity extends Activity {
    //    private SharedPreferences sp;
//    private Editor ed;
    private EditText edittext_qiugou_product_title, edittext_qiugou_product_style, edittext_product_number,
            edittext_product_money, edittext_product_beizhu;
    private LinearLayout layout;
    private ListView show_listview;
    private PopupWindow show_popupWindow;
    private Button want_buy_fenlei_button;
    private ArrayList<YiJi_Class> fenlei_list = new ArrayList<YiJi_Class>();
    private int fenlei_id;
    private TextView want_buy_submit, want_buy_product_text;
    private RelativeLayout relative_layout_send_buy_product_back;
    private ProgressDialog pd;
    private LinearLayout linear_product_style, linear_product_number;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {

                show_listview.setAdapter(new MyAdapter());
                show_listview.setOnItemClickListener(new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        fenlei_id = fenlei_list.get(position).getId();
                        want_buy_fenlei_button.setText(fenlei_list.get(position).getName());
                        if (show_popupWindow != null) {
                            show_popupWindow.dismiss();
                            show_popupWindow = null;
                        }
                    }
                });
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__send__want__buy__product);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        edittext_qiugou_product_title = (EditText) findViewById(R.id.edittext_qiugou_product_title);
        edittext_qiugou_product_style = (EditText) findViewById(R.id.edittext_qiugou_product_style);

        want_buy_product_text = (TextView) findViewById(R.id.want_buy_product_text);
        linear_product_style = (LinearLayout) findViewById(R.id.linear_product_style);
        linear_product_number = (LinearLayout) findViewById(R.id.linear_product_number);
        edittext_product_number = (EditText) findViewById(R.id.edittext_product_number);
        if (getIntent().getIntExtra("come_from_fuwu_send_buy", 0) == Contant.come_from_fuwu_send_buy) {
            //发布服务求购
            want_buy_product_text.setText("求购服务");
            linear_product_style.setVisibility(View.GONE);
            linear_product_number.setVisibility(View.GONE);
            edittext_qiugou_product_style.setVisibility(View.GONE);
            edittext_product_number.setVisibility(View.GONE);
            edittext_qiugou_product_title.setHint("求购服务");
        } else if (getIntent().getIntExtra("come_from_fuwu_send_buy", 0) == Contant.come_from_product_send_buy) {
            //发布产品求购
            want_buy_product_text.setText("求购产品");
            linear_product_style.setVisibility(View.VISIBLE);
            edittext_qiugou_product_style.setVisibility(View.VISIBLE);
            linear_product_number.setVisibility(View.VISIBLE);
            edittext_product_number.setVisibility(View.VISIBLE);
        }

        edittext_product_money = (EditText) findViewById(R.id.edittext_product_money);
        edittext_product_beizhu = (EditText) findViewById(R.id.edittext_product_beizhu);
        want_buy_fenlei_button = (Button) findViewById(R.id.want_buy_fenlei_button);
        want_buy_submit = (TextView) findViewById(R.id.want_buy_submit);
        relative_layout_send_buy_product_back = (RelativeLayout) findViewById(R.id.relative_layout_send_buy_product_back);
        pd = new ProgressDialog(this);
        want_buy_fenlei_button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Photo_show();
                if (getIntent().getIntExtra("come_from_fuwu_send_buy", 0) == Contant.come_from_product_send_buy) {
                    //请求的是产品的分类
                    get_fenlei();
                } else if (getIntent().getIntExtra("come_from_fuwu_send_buy", 0) == Contant.come_from_fuwu_send_buy) {
                    //请求的是服务的分类
                    get_fuwu_fenlei();
                }
                show_popupWindow.showAtLocation(findViewById(R.id.relative_want_buy), Gravity.BOTTOM, 0, 0);
            }
        });

        want_buy_submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                pd.show();
                if (getIntent().getIntExtra("come_from_fuwu_send_buy", 0) == Contant.come_from_product_send_buy) {
                    //发布产品求购提交
                    submit_want_buy();
                } else if (getIntent().getIntExtra("come_from_fuwu_send_buy", 0) == Contant.come_from_fuwu_send_buy) {
                    //发布服务求购提交
                    submit_fuwu_buy();
                }
            }
        });

        relative_layout_send_buy_product_back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Main_Send_Want_Buy_ProductActivity.this.finish();
            }
        });
    }

    /**
     * 发布产品求购数据请求
     */
    public void submit_want_buy() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("title", edittext_qiugou_product_title.getText().toString());
        map.put("details", edittext_product_beizhu.getText().toString());//备注
        map.put("model", edittext_qiugou_product_style.getText().toString());//型号
        map.put("price", edittext_product_money.getText().toString());//价格
        map.put("parent", fenlei_id);
        map.put("dw", edittext_product_number.getText().toString());//产品数量

        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.want_buy,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(Main_Send_Want_Buy_ProductActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {
                        Main_Send_Want_Buy_ProductActivity.this.finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(Main_Send_Want_Buy_ProductActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(30 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    /**
     * 发布服务求购数据请求
     */
    public void submit_fuwu_buy() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("title", edittext_qiugou_product_title.getText().toString());
        map.put("details", edittext_product_beizhu.getText().toString());//备注
        map.put("price", edittext_product_money.getText().toString());//价格
        map.put("parent", fenlei_id);
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.want_buy_fuwu,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(Main_Send_Want_Buy_ProductActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {
                        Main_Send_Want_Buy_ProductActivity.this.finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(Main_Send_Want_Buy_ProductActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(30 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    /**
     * 请求的是产品的分类
     */
    public void get_fenlei() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("cid", 0);
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.product_tag,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        JSONArray array = response.getJSONArray("data");
                        fenlei_list.clear();
                        if (array.length() == 0) {
                            if (show_popupWindow != null) {
                                show_popupWindow.dismiss();
                            }
                        } else {
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject OBJECT = array.getJSONObject(i);
                                YiJi_Class mYiJi_Class = new YiJi_Class();
                                mYiJi_Class.setId(OBJECT.getInt("id"));
                                mYiJi_Class.setName(OBJECT.getString("name"));
                                fenlei_list.add(mYiJi_Class);
                            }
                            handler.sendEmptyMessage(1);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    /**
     * 请求的是服务的分类
     */
    public void get_fuwu_fenlei() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("cid", 0);
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.geren_fuwu_fenlei,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        JSONArray array1 = response.getJSONArray("data");
                        JSONArray array = array1.getJSONArray(0);
                        fenlei_list.clear();
                        if (array.length() == 0) {
                            if (show_popupWindow != null) {
                                show_popupWindow.dismiss();
                            }
                        } else {
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject OBJECT = array.getJSONObject(i);
                                YiJi_Class mYiJi_Class = new YiJi_Class();
                                mYiJi_Class.setId(OBJECT.getInt("id"));
                                mYiJi_Class.setName(OBJECT.getString("name"));
                                fenlei_list.add(mYiJi_Class);
                            }
                            handler.sendEmptyMessage(1);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    private void Photo_show() {
        layout = (LinearLayout) LayoutInflater.from(
                Main_Send_Want_Buy_ProductActivity.this).inflate(
                R.layout.information_shoow_photo, null);
        show_listview = (ListView) layout.findViewById(R.id.information_photo_listview);

        show_listview.setCacheColorHint(0);
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        show_popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        show_popupWindow.setBackgroundDrawable(new BitmapDrawable());
        show_popupWindow.setHeight(wm.getDefaultDisplay().getHeight() / 2);
        show_popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        show_popupWindow.update();
        show_popupWindow.setOutsideTouchable(true);
        show_popupWindow.setFocusable(true);
        show_popupWindow.setContentView(layout);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        pd.cancel();
        pd = null;
    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return fenlei_list.size();
        }

        @Override
        public Object getItem(int arg0) {
            return arg0;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder mHolder;
            if (convertView == null) {
                mHolder = new Holder();
                convertView = View.inflate(Main_Send_Want_Buy_ProductActivity.this, R.layout.listview_item_layout, null);
                mHolder.place_text = (TextView) convertView.findViewById(R.id.place_text);
                convertView.setTag(mHolder);
            }
            mHolder = (Holder) convertView.getTag();
            mHolder.place_text.setText(fenlei_list.get(position).getName());
            return convertView;
        }
    }

    class Holder {
        TextView place_text;
    }
}
